﻿using System;
using GC_VKMD.BusinessEntities.Abstractions.Interfaces.Vkontakte;
using GC_VKMD.BusinessEntities.Enums.Vkontakte;
using GC_VKMD.BusinessEntities.Vkontakte;
using GC_VKMD.MusicDownloader.Abstractions.Interfaces.Factories.Managers;
using GC_VKMD.MusicDownloader.Abstractions.Interfaces.Helpers;
using GC_VKMD.MusicDownloader.Abstractions.Interfaces.Managers;
using GC_VKMD.MusicDownloader.Helpers.Parameters;

namespace GC_VKMD.MusicDownloader.Helpers
{
	public class VKMusicDownloader : IVKMusicDownloader
	{
		#region Variables

		private readonly IVKServiceFactory _vkServiceFactory;
		private readonly IVKAudioFileManager _vkAudioFileManager;

		#endregion

		#region Constructors

		public VKMusicDownloader(IVKServiceFactory vkServiceFactory, IVKAudioFileManager vkAudioFileManager)
		{
			if (vkServiceFactory == null)
				throw new ArgumentNullException(string.Format("vkServiceFactory"));
			_vkServiceFactory = vkServiceFactory;

			if (vkAudioFileManager == null)
				throw new ArgumentNullException(string.Format("vkAudioFileManager"));
			_vkAudioFileManager = vkAudioFileManager;
		}

		#endregion

		#region IVKMusicDownloader Members

		public IReport DownloadMusic(VKMusicDownloaderParameters parameters)
		{
			var report = new Report();

			if (parameters == null)
				report.Messages.Add(new ReportMessage("Некорректные параметры для доступа к скачиванию музыки из vk.com!", ReportMessageType.Error));
			else
			{
				try
				{
					var service = _vkServiceFactory.Create(parameters.Token, parameters.UserId);
					if (service != null)
					{
						var audioTracksCount = parameters.AudioTracksCount;
						if (parameters.AudioTracksCount == 0)
							audioTracksCount = service.GetAudioTracksCount();

						if (parameters.FilesCountAction != null)
							parameters.FilesCountAction(audioTracksCount);

						var music = service.GetAudio(audioTracksCount);
						if (music == null)
							throw new InvalidOperationException(string.Format("Приложение не может получить список аудио с вашей страницы!"));

						_vkAudioFileManager.DownloadFiles(music, parameters.FolderPath,
							s =>
							{
								report.Messages.Add(new ReportMessage(s));
								if (parameters.SuccessfulDownloadFileAction != null)
									parameters.SuccessfulDownloadFileAction(s);
							},
							s =>
							{
								report.Messages.Add(new ReportMessage(s, ReportMessageType.Error));
								if (parameters.ErrorDownloadFileAction != null)
									parameters.ErrorDownloadFileAction(s);
							});
					}
				}
				catch (Exception ex)
				{
					report.Messages.Add(new ReportMessage(ex.Message, ReportMessageType.Error));
				}
			}

			return report;
		}

		#endregion
	}
}
